// 待办事项应用逻辑

// DOM 元素
const todoInput = document.getElementById('todo-input');
const addButton = document.getElementById('add-button');
const todoList = document.getElementById('todo-list');
const filterButtons = document.querySelectorAll('.filter-btn');
const prioritySelect = document.getElementById('priority-select');
const dueDateInput = document.getElementById('due-date-input');
const progressBar = document.getElementById('progress-bar');
const totalTasksElement = document.getElementById('total-tasks');
const completedTasksElement = document.getElementById('completed-tasks');
// 星座相关元素
const constellationSelect = document.getElementById('constellation-select');
const getHoroscopeBtn = document.getElementById('get-horoscope-btn');
const horoscopeResult = document.getElementById('horoscope-result');

// 待办事项数组
let todos = JSON.parse(localStorage.getItem('gameTodos')) || [
    {id: 1, text: '玩《塞尔达传说：王国之泪》', completed: false, priority: 'high', dueDate: '2023-12-31'},
    {id: 2, text: '尝试《博德之门3》', completed: true, priority: 'medium', dueDate: '2023-11-15'},
    {id: 3, text: '体验《星空》', completed: false, priority: 'low', dueDate: '2024-01-20'}
];
let currentFilter = 'all';

// 渲染待办事项列表
function renderTodos() {
    // 清空列表
    todoList.innerHTML = '';

    // 过滤待办事项
    let filteredTodos = todos;
    if (currentFilter === 'active') {
        filteredTodos = todos.filter(todo => !todo.completed);
    } else if (currentFilter === 'completed') {
        filteredTodos = todos.filter(todo => todo.completed);
    } else if (currentFilter === 'high') {
        filteredTodos = todos.filter(todo => todo.priority === 'high');
    }

    // 排序待办事项：高优先级在前，然后是截止日期近的
    filteredTodos.sort((a, b) => {
        // 优先级排序
        if (a.priority !== b.priority) {
            return a.priority === 'high' ? -1 : (b.priority === 'high' ? 1 : 0);
        }
        // 截止日期排序
        if (a.dueDate && b.dueDate) {
            return new Date(a.dueDate) - new Date(b.dueDate);
        }
        return 0;
    });

    // 渲染每个待办事项
    filteredTodos.forEach(todo => {
        const todoItem = document.createElement('li');
        todoItem.className = 'todo-item' + (todo.completed ? ' completed' : '');
        todoItem.dataset.id = todo.id;

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.checked = todo.completed;
        checkbox.addEventListener('change', () => toggleTodo(todo.id));

        const todoText = document.createElement('span');
        todoText.className = 'todo-text';
        todoText.textContent = todo.text;

        // 优先级标签
        const priorityTag = document.createElement('span');
        priorityTag.className = 'priority-tag priority-' + todo.priority;
        priorityTag.textContent = todo.priority === 'low' ? '低' : (todo.priority === 'medium' ? '中' : '高');

        // 截止日期
        let dueDateElement = null;
        if (todo.dueDate) {
            dueDateElement = document.createElement('span');
            dueDateElement.className = 'due-date';
            // 格式化日期为 YYYY-MM-DD
            const date = new Date(todo.dueDate);
            dueDateElement.textContent = date.toISOString().split('T')[0];

            // 如果截止日期已过且任务未完成，添加特殊样式
            if (new Date(todo.dueDate) < new Date() && !todo.completed) {
                dueDateElement.style.color = '#e74c3c';
                dueDateElement.style.fontWeight = 'bold';
            }
        }

        const deleteButton = document.createElement('button');
        deleteButton.className = 'delete-btn';
        deleteButton.textContent = '删除';
        deleteButton.addEventListener('click', () => deleteTodo(todo.id));

        todoItem.appendChild(checkbox);
        todoItem.appendChild(todoText);
        todoItem.appendChild(priorityTag);
        if (dueDateElement) {
            todoItem.appendChild(dueDateElement);
        }
        todoItem.appendChild(deleteButton);
        todoList.appendChild(todoItem);
    });

    // 更新计数
    updateCounts();
}

// 添加新的待办事项
function addTodo() {
    const text = todoInput.value.trim();
    const priority = prioritySelect.value;
    const dueDate = dueDateInput.value;

    if (text === '') {
        alert('请输入游戏名称！');
        return;
    }

    const newTodo = {
        id: Date.now(),
        text: text,
        completed: false,
        priority: priority,
        dueDate: dueDate
    };

    todos.push(newTodo);
    saveTodos();
    renderTodos();

    // 清空输入框
    todoInput.value = '';
    dueDateInput.value = '';
}

// 切换待办事项状态
function toggleTodo(id) {
    const todo = todos.find(todo => todo.id === id);
    if (todo) {
        todo.completed = !todo.completed;
        saveTodos();
        renderTodos();
    }
}

// 删除待办事项
function deleteTodo(id) {
    todos = todos.filter(todo => todo.id !== id);
    saveTodos();
    renderTodos();
}

// 保存待办事项到本地存储
function saveTodos() {
    localStorage.setItem('gameTodos', JSON.stringify(todos));
}

// 更新任务计数和进度条
function updateCounts() {
    const totalTasks = todos.length;
    const completedTasks = todos.filter(todo => todo.completed).length;

    totalTasksElement.textContent = totalTasks;
    completedTasksElement.textContent = completedTasks;

    // 更新进度条
    if (totalTasks === 0) {
        progressBar.style.width = '0%';
    } else {
        const progressPercentage = (completedTasks / totalTasks) * 100;
        progressBar.style.width = `${progressPercentage}%`;
    }
}

// 设置过滤器
function setFilter(filter) {
    currentFilter = filter;
    filterButtons.forEach(button => {
        button.classList.remove('active');
        if (button.dataset.filter === filter) {
            button.classList.add('active');
        }
    });
    renderTodos();

    // 星座运势相关功能
    function getHoroscope() {
        const constellationId = constellationSelect.value;
        const apiUrl = `https://userapi-newtabpro.newtabpro.cn/getxzinfo?xid=${constellationId}`;

        // 显示加载状态
        getHoroscopeBtn.textContent = '加载中...';
        getHoroscopeBtn.disabled = true;

        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error('API请求失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 1 && data.data) {
                    renderHoroscope(data.data);
                } else {
                    showError('获取星座运势失败');
                }
            })
            .catch(error => {
                console.error('获取星座运势错误:', error);
                showError('获取星座运势时发生错误');
            })
            .finally(() => {
                // 恢复按钮状态
                getHoroscopeBtn.textContent = '获取运势';
                getHoroscopeBtn.disabled = false;
            });
    }

    function renderHoroscope(data) {
        // 清空结果容器
        horoscopeResult.innerHTML = '';

        // 创建星座运势HTML结构
        const horoscopeHTML = `
            <div class="horoscope-header">
                <img src="${data.thumb}" alt="星座图标" class="horoscope-icon">
                <div class="horoscope-title">
                    ${getConstellationNameById(constellationSelect.value)}今日运势
                </div>
            </div>
            <div class="horoscope-lucky">
                <div class="horoscope-lucky-item">
                    <div class="horoscope-lucky-label">幸运颜色</div>
                    <div class="horoscope-lucky-value">${data.luckycolor}</div>
                </div>
                <div class="horoscope-lucky-item">
                    <div class="horoscope-lucky-label">幸运数字</div>
                    <div class="horoscope-lucky-value">${data.luckynumber}</div>
                </div>
                <div class="horoscope-lucky-item">
                    <div class="horoscope-lucky-label">速配星座</div>
                    <div class="horoscope-lucky-value">${data.speeddating}</div>
                </div>
            </div>
            <div class="horoscope-fortunes">
                <div class="horoscope-fortune-item">
                    <div class="horoscope-fortune-label">整体运势</div>
                    <div class="horoscope-fortune-value fortune-${data.fortune}">${getFortuneText(data.fortune)}</div>
                </div>
                <div class="horoscope-fortune-item">
                    <div class="horoscope-fortune-label">爱情运势</div>
                    <div class="horoscope-fortune-value fortune-${data.lovefortune}">${getFortuneText(data.lovefortune)}</div>
                </div>
                <div class="horoscope-fortune-item">
                    <div class="horoscope-fortune-label">事业学业</div>
                    <div class="horoscope-fortune-value fortune-${data.careerstudies}">${getFortuneText(data.careerstudies)}</div>
                </div>
                <div class="horoscope-fortune-item">
                    <div class="horoscope-fortune-label">财富运势</div>
                    <div class="horoscope-fortune-value fortune-${data.fortunefortune}">${getFortuneText(data.fortunefortune)}</div>
                </div>
            </div>
            <div class="horoscope-intro">
                <div class="horoscope-fortune-label">今日概述</div>
                <div class="horoscope-fortune-value">${data.introduction || '暂无详细信息'}</div>
            </div>
        `;

        // 添加到结果容器
        horoscopeResult.innerHTML = horoscopeHTML;

        // 显示结果
        horoscopeResult.classList.add('visible');
    }

    function getConstellationNameById(id) {
        const constellations = [
            '', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
            '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
        ];
        return constellations[id] || '未知星座';
    }

    function getFortuneText(level) {
        switch (level) {
            case '4':
                return '极佳';
            case '3':
                return '良好';
            case '2':
                return '一般';
            case '1':
                return '较差';
            default:
                return '未知';
        }
    }

    function showError(message) {
        horoscopeResult.innerHTML = `
            <div class="error-message">
                ${message}
            </div>
        `;
        horoscopeResult.classList.add('visible');
    }

    // 添加星座运势事件监听
    getHoroscopeBtn.addEventListener('click', getHoroscope);
}

// 事件监听器
addButton.addEventListener('click', addTodo);

todoInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        addTodo();
    }
});

filterButtons.forEach(button => {
    button.addEventListener('click', () => {
        setFilter(button.dataset.filter);
    });
});

// 初始化
renderTodos();

// 星座运势相关功能
function getHoroscope() {
    const constellationId = constellationSelect.value;
    const apiUrl = `https://userapi-newtabpro.newtabpro.cn/getxzinfo?xid=${constellationId}`;

    // 显示加载状态
    getHoroscopeBtn.textContent = '加载中...';
    getHoroscopeBtn.disabled = true;

    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('API请求失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 1 && data.data) {
                renderHoroscope(data.data);
            } else {
                showError('获取星座运势失败');
            }
        })
        .catch(error => {
            console.error('获取星座运势错误:', error);
            showError('获取星座运势时发生错误');
        })
        .finally(() => {
            // 恢复按钮状态
            getHoroscopeBtn.textContent = '获取运势';
            getHoroscopeBtn.disabled = false;
        });
}

function renderHoroscope(data) {
    // 清空结果容器
    horoscopeResult.innerHTML = '';

    // 创建星座运势HTML结构
    const horoscopeHTML = `
        <div class="horoscope-header">
            <img src="${data.thumb}" alt="星座图标" class="horoscope-icon">
            <div class="horoscope-title">
                ${getConstellationNameById(constellationSelect.value)}今日运势
            </div>
        </div>
        <div class="horoscope-lucky">
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运颜色</div>
                <div class="horoscope-lucky-value">${data.luckycolor}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运数字</div>
                <div class="horoscope-lucky-value">${data.luckynumber}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">速配星座</div>
                <div class="horoscope-lucky-value">${data.speeddating}</div>
            </div>
        </div>
        <div class="horoscope-fortunes">
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">整体运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortune}">${getFortuneText(data.fortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">爱情运势</div>
                <div class="horoscope-fortune-value fortune-${data.lovefortune}">${getFortuneText(data.lovefortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">事业学业</div>
                <div class="horoscope-fortune-value fortune-${data.careerstudies}">${getFortuneText(data.careerstudies)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">财富运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortunefortune}">${getFortuneText(data.fortunefortune)}</div>
            </div>
        </div>
        <div class="horoscope-intro">
            <div class="horoscope-fortune-label">今日概述</div>
            <div class="horoscope-fortune-value">${data.introduction || '暂无详细信息'}</div>
        </div>
    `;

    // 添加到结果容器
    horoscopeResult.innerHTML = horoscopeHTML;

    // 显示结果
    horoscopeResult.classList.add('visible');
}

function getConstellationNameById(id) {
    const constellations = [
        '', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
        '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
    ];
    return constellations[id] || '未知星座';
}

function getFortuneText(level) {
    switch (level) {
        case '4':
            return '极佳';
        case '3':
            return '良好';
        case '2':
            return '一般';
        case '1':
            return '较差';
        default:
            return '未知';
    }
}

function showError(message) {
    horoscopeResult.innerHTML = `
        <div class="error-message">
            ${message}
        </div>
    `;
    horoscopeResult.classList.add('visible');
}

// 添加星座运势事件监听
getHoroscopeBtn.addEventListener('click', getHoroscope);

function renderHoroscope(data) {
    // 清空结果容器
    horoscopeResult.innerHTML = '';

    // 创建星座运势HTML结构
    const horoscopeHTML = `
        <div class="horoscope-header">
            <img src="${data.thumb}" alt="星座图标" class="horoscope-icon">
            <div class="horoscope-title">
                ${getConstellationNameById(constellationSelect.value)}今日运势
            </div>
        </div>
        <div class="horoscope-lucky">
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运颜色</div>
                <div class="horoscope-lucky-value">${data.luckycolor}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运数字</div>
                <div class="horoscope-lucky-value">${data.luckynumber}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">速配星座</div>
                <div class="horoscope-lucky-value">${data.speeddating}</div>
            </div>
        </div>
        <div class="horoscope-fortunes">
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">整体运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortune}">${getFortuneText(data.fortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">爱情运势</div>
                <div class="horoscope-fortune-value fortune-${data.lovefortune}">${getFortuneText(data.lovefortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">事业学业</div>
                <div class="horoscope-fortune-value fortune-${data.careerstudies}">${getFortuneText(data.careerstudies)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">财富运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortunefortune}">${getFortuneText(data.fortunefortune)}</div>
            </div>
        </div>
        <div class="horoscope-intro">
            <div class="horoscope-fortune-label">今日概述</div>
            <div class="horoscope-fortune-value">${data.introduction || '暂无详细信息'}</div>
        </div>
    `;

    // 添加到结果容器
    horoscopeResult.innerHTML = horoscopeHTML;

    // 显示结果
    horoscopeResult.classList.add('visible');
}

function getConstellationNameById(id) {
    const constellations = [
        '', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
        '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
    ];
    return constellations[id] || '未知星座';
}

function getFortuneText(level) {
    switch (level) {
        case '4':
            return '极佳';
        case '3':
            return '良好';
        case '2':
            return '一般';
        case '1':
            return '较差';
        default:
            return '未知';
    }
}

function showError(message) {
    horoscopeResult.innerHTML = `
        <div class="error-message">
            ${message}
        </div>
    `;
    horoscopeResult.classList.add('visible');
}

// 添加星座运势事件监听
getHoroscopeBtn.addEventListener('click', getHoroscope);

function renderHoroscope(data) {
    // 清空结果容器
    horoscopeResult.innerHTML = '';

    // 创建星座运势HTML结构
    const horoscopeHTML = `
        <div class="horoscope-header">
            <img src="${data.thumb}" alt="星座图标" class="horoscope-icon">
            <div class="horoscope-title">
                ${getConstellationNameById(constellationSelect.value)}今日运势
            </div>
        </div>
        <div class="horoscope-lucky">
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运颜色</div>
                <div class="horoscope-lucky-value">${data.luckycolor}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运数字</div>
                <div class="horoscope-lucky-value">${data.luckynumber}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">速配星座</div>
                <div class="horoscope-lucky-value">${data.speeddating}</div>
            </div>
        </div>
        <div class="horoscope-fortunes">
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">整体运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortune}">${getFortuneText(data.fortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">爱情运势</div>
                <div class="horoscope-fortune-value fortune-${data.lovefortune}">${getFortuneText(data.lovefortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">事业学业</div>
                <div class="horoscope-fortune-value fortune-${data.careerstudies}">${getFortuneText(data.careerstudies)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">财富运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortunefortune}">${getFortuneText(data.fortunefortune)}</div>
            </div>
        </div>
        <div class="horoscope-intro">
            <div class="horoscope-fortune-label">今日概述</div>
            <div class="horoscope-fortune-value">${data.introduction || '暂无详细信息'}</div>
        </div>
    `;

    // 添加到结果容器
    horoscopeResult.innerHTML = horoscopeHTML;

    // 显示结果
    horoscopeResult.classList.add('visible');
}

function getConstellationNameById(id) {
    const constellations = [
        '', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
        '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
    ];
    return constellations[id] || '未知星座';
}

function getFortuneText(level) {
    switch (level) {
        case '4':
            return '极佳';
        case '3':
            return '良好';
        case '2':
            return '一般';
        case '1':
            return '较差';
        default:
            return '未知';
    }
}

function showError(message) {
    horoscopeResult.innerHTML = `
        <div class="error-message">
            ${message}
        </div>
    `;
    horoscopeResult.classList.add('visible');
}

// 添加星座运势事件监听
getHoroscopeBtn.addEventListener('click', getHoroscope);

function renderHoroscope(data) {
    // 清空结果容器
    horoscopeResult.innerHTML = '';

    // 创建星座运势HTML结构
    const horoscopeHTML = `
        <div class="horoscope-header">
            <img src="${data.thumb}" alt="星座图标" class="horoscope-icon">
            <div class="horoscope-title">
                ${getConstellationNameById(constellationSelect.value)}今日运势
            </div>
        </div>
        <div class="horoscope-lucky">
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运颜色</div>
                <div class="horoscope-lucky-value">${data.luckycolor}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">幸运数字</div>
                <div class="horoscope-lucky-value">${data.luckynumber}</div>
            </div>
            <div class="horoscope-lucky-item">
                <div class="horoscope-lucky-label">速配星座</div>
                <div class="horoscope-lucky-value">${data.speeddating}</div>
            </div>
        </div>
        <div class="horoscope-fortunes">
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">整体运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortune}">${getFortuneText(data.fortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">爱情运势</div>
                <div class="horoscope-fortune-value fortune-${data.lovefortune}">${getFortuneText(data.lovefortune)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">事业学业</div>
                <div class="horoscope-fortune-value fortune-${data.careerstudies}">${getFortuneText(data.careerstudies)}</div>
            </div>
            <div class="horoscope-fortune-item">
                <div class="horoscope-fortune-label">财富运势</div>
                <div class="horoscope-fortune-value fortune-${data.fortunefortune}">${getFortuneText(data.fortunefortune)}</div>
            </div>
        </div>
        <div class="horoscope-intro">
            <div class="horoscope-fortune-label">今日概述</div>
            <div class="horoscope-fortune-value">${data.introduction || '暂无详细信息'}</div>
        </div>
    `;

    // 添加到结果容器
    horoscopeResult.innerHTML = horoscopeHTML;

    // 显示结果
    horoscopeResult.classList.add('visible');
}

function getConstellationNameById(id) {
    const constellations = [
        '', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
        '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
    ];
    return constellations[id] || '未知星座';
}

function getFortuneText(level) {
    switch (level) {
        case '4':
            return '极佳';
        case '3':
            return '良好';
        case '2':
            return '一般';
        case '1':
            return '较差';
        default:
            return '未知';
    }
}

function showError(message) {
    horoscopeResult.innerHTML = `
        <div class="error-message">
            ${message}
        </div>
    `;
    horoscopeResult.classList.add('visible');
}

// 添加星座运势事件监听
getHoroscopeBtn.addEventListener('click', getHoroscope);